﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using GTasksPlus.Code;
using GTasksPlus.Model;

namespace GTasksPlus.ViewModels
{
    public class TaskViewModel : INotifyPropertyChanged
    {
        public string Id { get; set; }

        #region Private Members

        private static ObservableCollection<TaskItem> _tasks;
        private TaskListItem _parentList = new TaskListItem();
        private bool _isDataLoaded;

        #endregion

        public bool IsDataLoaded
        {
            get { return _isDataLoaded; }
            set
            {
                _isDataLoaded = value;
                OnPropertyChanged("IsDataLoaded");
            }
        }

        public TaskViewModel(string id)
        {
            TaskItem = null;
            Id = id;
            LoadData();
        }

        public TaskViewModel()
        {
            
        }

        public void LoadData()
        {
            TaskListHelper.GetSpecificTaskList(Id, SetTaskListItem);
        }

        private void SetTaskListItem(TaskListItem obj)
        {
            ParentList = obj;
            TaskListHelper.GetTasksForList(Id, SetTasks);
        }

        private void SetTasks(List<TaskItem> obj)
        {
            TaskItem = new ObservableCollection<TaskItem>(obj);
        }

        public TaskListItem ParentList
        {
            get { return _parentList; }
            set
            {
                _parentList = value; OnPropertyChanged("ParentList");
            }
        }

        /// <summary>
        /// A collection for TaskListItem objects.
        /// </summary>
        public ObservableCollection<TaskItem> TaskItem
        {
            get { return _tasks ?? new ObservableCollection<TaskItem>(); }
            set
            {
                _tasks = value;
                if (_tasks != null)
                {
                    OnPropertyChanged("TaskItem");
                    IsDataLoaded = true;
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}